package com.cn.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import com.cn.domain.User;

public class ProxyFactory {
	@SuppressWarnings("unchecked")
	public static <T> T getProxy(final T t){
		
		return (T)Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), t.getClass().getInterfaces(), new InvocationHandler() {
			
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				//1、获得方法的注解权限
				Privilege annocation = method.getAnnotation(Privilege.class);
				if(annocation==null){
					//如果没有获得到，执行方法
					try {
						return method.invoke(t, args);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException(e.getCause().getMessage());
					}
				}
				//2、获得到，说明有权限限制
				//3、获得当前用户
				User u = CurrentUserUtils.get();
				if(u==null){
					//没有获得当前用户，抛异常，提示 需要登录
					throw new RuntimeException("请登录");
				}
				//4、获得当前用户的权限
				String sql ="SELECT " +
						"  p.name              " +
					    " FROM USER u,         " +
					    " user_role ur,        " +
					    " role r,              " +
					    " role_privilege rp,   " +
					    " privilege p          " +
					    " WHERE u.id = ur.uid  " +
					    " AND ur.rid = r.id    " +
					    " AND r.id = rp.rid    " +
					    " AND rp.pid = p.id    " +
					    		"and u.id = ?";
				Connection conn = JdbcUtils.getConnection();
				QueryRunner qr = new QueryRunner();
				List<Object> list = qr.query(conn, sql, new ColumnListHandler(),u.getId());
				//5、比较当前用户是否有该方法有的权限
				String pname = annocation.value();
				if(!list.contains(pname)){
					//没有，抛异常，提示没有权限
					throw new RuntimeException("您没有该权限！");
				}else{
					//有，执行该方法
					try {
						return method.invoke(t, args);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						throw new RuntimeException(e.getCause().getMessage());
					}
				}
				
			}
		});
	}
}
